<script setup>
import {reactive, ref} from 'vue'
import {addResult, deleteResult, editResult, getResultById, queryResultPage} from "@/api/result.js";
import router from "@/router/index.js";
import CoverUploader from '@/components/UploadAppCover.vue';
import {Message} from '@arco-design/web-vue';
import TitleComponent from "@/components/TitleComponent.vue";

const pageForm = ref({
  pageSize: 12,
  currentPage: 1,
  appId: '',
  resultName: '',
  resultDesc: ''
})
const id = ref(0)
const pageFormRef = ref()
const total = ref(0)

const tableLoading = ref(false)
const tableData = ref([])

const tipDialog = ref(false)

const columns = [
  {
    title: '名称',
    dataIndex: 'resultName',
    ellipsis: true,
    tooltip: true,
    fixed: 'left',
    width: 90
  },
  {
    title: '结果描述',
    dataIndex: 'resultDesc',
    ellipsis: true,
    tooltip: true,
  },
  {
    title: '属性集合',
    dataIndex: 'resultProp',
    ellipsis: true,
    tooltip: true,
    slotName: 'resultPropSlot'
  },
  {
    title: '得分范围(以上)',
    dataIndex: 'resultScoreRange',
    ellipsis: true,
    tooltip: true,
    sortable: {
      sortDirections: ['ascend', 'descend']
    }
  },
  {
    title: '创建时间',
    dataIndex: 'createTime',
    width: 180
  },
  {
    title: '更新时间',
    dataIndex: 'updateTime',
    width: 180
  },
  {
    title: '操作',
    dataIndex: 'action',
    slotName: 'optional',
    width: 200,
  }
];

const selectedKeys = ref([]);

const rowSelection = reactive({
  type: 'checkbox',
  showCheckedAll: true,
  onlyCurrent: false,
});

// 删除评分结果相关
const handleDelete = () => {
  if (selectedKeys.value.length === 0) {
    Message.warning('请先选择要删除的评分结果');
    return;
  }

  deleteResult(selectedKeys.value)
    .then(res => {
      if (res.data.code === 1) {
        Message.success('删除评分结果成功');
        selectedKeys.value = [];
        submitPageForm(1); // 刷新列表
      } else {
        Message.error(res.data.message || '删除评分结果失败');
      }
    })
    .catch(error => {
      console.error(error);
      Message.error('删除评分结果失败');
    });
};

// 详情弹窗相关
const detailVisible = ref(false);
const resultDetail = ref({});

const handleViewDetail = (id) => {
  getResultById(id)
    .then(res => {
      if (res.data.code === 1) {
        resultDetail.value = res.data.data;
        detailVisible.value = true;
      } else {
        Message.error(res.data.message || '获取评分结果详情失败');
      }
    })
    .catch(error => {
      console.error(error);
      Message.error('获取评分结果详情失败');
    });
};

// 新增评分结果相关
const visible = ref(false);
const addFormRef = ref();
const addForm = ref({
  resultName: '',
  resultDesc: '',
  resultPicture: '',
  resultProp: [],
  resultScoreRange: null,
  appId: ''
});

// 编辑评分结果相关
const editVisible = ref(false);
const editFormRef = ref();
const editForm = ref({
  id: '',
  resultName: '',
  resultDesc: '',
  resultPicture: '',
  resultProp: [],
  resultScoreRange: null,
  appId: ''
});

const editFormRules = {
  resultName: [
    {
      required: true,
      pattern: /^[a-zA-Z0-9\u4e00-\u9fff]{1,16}$/,
      message: '结果名称必须为1 - 16位中英文数字'
    }
  ],
  resultDesc: [
    {
      required: true,
      pattern: /^.{1,100}$/,
      message: '结果描述必须为1 - 100个字符'
    }
  ],
  resultProp: [
    {
      required: true,
      pattern: /^.{1,50}$/,
      message: '结果属性集合必须为1 - 50个字符'
    }
  ],
  resultScoreRange: [
    {
      required: true,
      min: 0,
      message: '得分范围必须为0及以上的数字'
    }
  ]
};

const addFormRules = {
  resultName: [
    {
      required: true,
      match: /^[a-zA-Z0-9\u4e00-\u9fff]{1,16}$/,
      message: '结果名称必须为1 - 16位中英文数字'
    }
  ],
  resultDesc: [
    {
      required: true,
      match: /^.{1,100}$/,
      message: '结果描述必须为1 - 100个字符'
    }
  ],
  resultProp: [
    {
      required: true,
      match: /^.{1,50}$/,
      message: '结果属性集合必须为1 - 50个字符'
    }
  ],
  resultScoreRange: [
    {
      required: true,
      min: 0,
      message: '得分范围必须为0及以上的数字'
    }
  ]
};

const handleAdd = () => {
  visible.value = true;
  addForm.value.appId = id.value;
};

const handleCancel = () => {
  visible.value = false;
  addFormRef.value?.resetFields();
};

// 编辑弹窗取消
const handleEditCancel = () => {
  editVisible.value = false;
  editFormRef.value?.resetFields();
};

const refUploader = ref(null)
const handleOk = () => {
  addFormRef.value?.validate(async (errors) => {
    if (!errors) {
      try {
        addForm.value.resultPicture = await refUploader.value.uploadImage()
        const res = await addResult(addForm.value)
        if (res.data.code === 1) {
          Message.success('新增评分结果成功');
          visible.value = false;
          addFormRef.value?.resetFields();
          submitPageForm(1); // 刷新列表
        } else {
          Message.error(res.data.message || '新增评分结果失败');
        }
      } catch (error) {
        console.error(error);
        Message.error('新增评分结果失败');
      }
    } else {
      console.log(errors);
    }
  });
};

const editRefUploader = ref(null)
// 编辑弹窗确认
const handleEditOk = () => {
  editFormRef.value?.validate(async (errors) => {
    if (!errors) {
      try {
        editForm.value.resultPicture = await editRefUploader.value.uploadImage()
        const res = await editResult(editForm.value)
        if (res.data.code === 1) {
          Message.success('编辑评分结果成功');
          editVisible.value = false;
          editFormRef.value?.resetFields();
          submitPageForm(1); // 刷新列表
        } else {
          Message.error(res.data.message || '编辑评分结果失败');
        }
      } catch (error) {
        console.error(error);
        Message.error('编辑评分结果失败');
      }
    } else {
      console.log(errors);
    }
  });
};

// 处理编辑按钮点击
const handleEdit = (record) => {
  getResultById(record.id)
    .then(res => {
      if (res.data.code === 1) {
        const data = res.data.data;
        editForm.value = {
          id: data.id,
          resultName: data.resultName,
          resultDesc: data.resultDesc,
          resultPicture: data.resultPicture,
          resultProp: data.resultProp,
          resultScoreRange: data.resultScoreRange,
          appId: data.appId
        };
        editVisible.value = true;
      } else {
        Message.error(res.data.message || '获取评分结果详情失败');
      }
    })
    .catch(error => {
      console.error(error);
      Message.error('获取评分结果详情失败');
    });
};

const submitPageForm = (flag) => {
  if (flag === 1) {
    pageForm.value.currentPage = 1
  }
  const params = router.currentRoute.value.params
  id.value = params.id
  pageForm.value.appId = id.value
  tableLoading.value = true
  queryResultPage(pageForm.value)
    .then(res => {
      if (res.data.code === 1) {
        tableData.value = res.data.data.records
        total.value = Number(res.data.data.total)
      }
    })
    .catch(error => {
      console.log(error)
    })
    .finally(() => {
      tableLoading.value = false
    })
}
submitPageForm()

const resetPageForm = () => {
  pageFormRef.value.resetFields()
}

const pageChange = (currentPage) => {
  pageForm.value.currentPage = currentPage
  submitPageForm()
}

// 标签内容变化事件
const addFormTagsChange = (value) => {
  if (value.length > 20) {
    Message.warning('最多只能添加20个元素！')
    addForm.value.resultProp = value.slice(0, 20)
  }
}

const editFormTagsChange = (value) => {
  if (value.length > 20) {
    Message.warning('最多只能添加20个元素！')
    editForm.value.resultProp = value.slice(0, 20)
  }
}
</script>

<template>
  <div id="scrolling-page">
    <a-card class="card">
      <title-component title-text="设置评分结果"></title-component>
      <div class="set-container">
        <div class="select-container">
          <a-form :model="pageForm" layout="inline" ref="pageFormRef">
            <a-form-item label="结果名称" field="resultName">
              <a-input v-model="pageForm.resultName" placeholder="请输入结果名称"></a-input>
            </a-form-item>
            <a-form-item label="结果描述" field="resultDesc">
              <a-input v-model="pageForm.resultDesc" placeholder="请输入结果描述"></a-input>
            </a-form-item>
            <a-form-item>
              <a-button type="primary" class="btn" @click="submitPageForm(1)">查询</a-button>
              <a-button type="outline" class="btn" @click="resetPageForm">重置</a-button>
            </a-form-item>
          </a-form>
        </div>
        <div class="button-container">
          <a-button shape="circle" status="warning" class="btn" @click="tipDialog = true">
            <icon-question-circle-fill/>
          </a-button>
          <a-button type="primary" class="btn" @click="router.push(`/score/ai/${id}`)">AI</a-button>
          <a-button type="primary" class="btn" @click="handleAdd">新增</a-button>
          <a-popconfirm
            content="确定要删除选中的评分结果吗？"
            @ok="handleDelete"
            position="br"
          >
            <a-button type="primary" status="danger" class="btn">删除</a-button>
          </a-popconfirm>
        </div>
      </div>
      <a-divider>评分结果管理</a-divider>
      <div class="table-container">
        <a-table
          stripe
          size="medium"
          :scroll="{ x: 1000 }"
          :loading="tableLoading"
          :pagination="false"
          row-key="id"
          :row-selection="rowSelection"
          v-model:selectedKeys="selectedKeys"
          :columns="columns"
          :data="tableData">
          <template #resultPropSlot="{ record }">
            <a-tag v-for="(item, index) in record.resultProp" :key="index" color="blue" style="margin-right: 3px">{{ item }}</a-tag>
          </template>
          <template #optional="{ record }">
            <a-button type="text" status="success" @click="handleEdit(record)">编辑</a-button>
            <a-button type="text" @click="handleViewDetail(record.id)">详情</a-button>
          </template>
        </a-table>
      </div>
      <a-divider/>
      <a-pagination
        size="small"
        :base-size="1"
        :buffer-size="1"
        :total="total"
        :default-page-size="12"
        :current="pageForm.currentPage"
        :page-size="pageForm.pageSize"
        @change="pageChange"
      />
    </a-card>

    <!-- 新增评分结果弹窗 -->
    <a-modal
      v-model:visible="visible"
      @cancel="handleCancel"
      @ok="handleOk"
      :width="300"
      title="新增评分结果">
      <a-form
        ref="addFormRef"
        :model="addForm"
        :rules="addFormRules"
        hide-asterisk
        @submit="handleOk">
        <a-form-item field="resultPicture" hide-label>
          <cover-uploader v-model="addForm.resultPicture" ref="refUploader"/>
        </a-form-item>
        <a-form-item field="resultName" hide-label validate-trigger="blur">
          <a-input v-model="addForm.resultName" placeholder="请输入结果名称"/>
        </a-form-item>
        <a-form-item field="resultDesc" hide-label validate-trigger="blur">
          <a-textarea
            v-model="addForm.resultDesc"
            placeholder="请输入结果描述"
            :max-length="100"
            show-word-limit
          />
        </a-form-item>
        <a-form-item field="resultProp" hide-label validate-trigger="blur">
          <a-input-tag v-model="addForm.resultProp" placeholder='请输入结果属性集合(Enter输入)' allow-clear @change="addFormTagsChange"/>
        </a-form-item>
        <a-form-item field="resultScoreRange" hide-label validate-trigger="blur">
          <a-input-number
            v-model="addForm.resultScoreRange"
            placeholder="请输入结果得分范围"
            :min="0"
            :step="1"
          />
        </a-form-item>
      </a-form>
    </a-modal>

    <!-- 评分结果详情弹窗 -->
    <a-modal
      v-model:visible="detailVisible"
      title="评分结果详情"
      :width="300"
      :footer="false"
    >
      <a-descriptions
        :column="1"
        :bordered="true"
        :size="'default'"
        :labelStyle="{ fontWeight: 'bold' }"
      >
        <a-descriptions-item label="结果图片" v-if="resultDetail.resultPicture">
          <div class="detail-image">
            <img :src="resultDetail.resultPicture" alt="结果图片" style="max-width: 100%; max-height: 200px;"/>
          </div>
        </a-descriptions-item>
        <a-descriptions-item label="结果名称">{{ resultDetail.resultName }}</a-descriptions-item>
        <a-descriptions-item label="结果描述">{{ resultDetail.resultDesc }}</a-descriptions-item>
        <a-descriptions-item label="属性集合">
          <a-tag v-for="(item, index) in resultDetail.resultProp" :key="index" color="blue" style="margin-right: 3px">{{ item }}</a-tag>
        </a-descriptions-item>
        <a-descriptions-item label="得分范围">{{ resultDetail.resultScoreRange }} 分及以上</a-descriptions-item>
        <a-descriptions-item label="创建用户">{{ resultDetail.createUser }}</a-descriptions-item>
        <a-descriptions-item label="创建时间">{{ resultDetail.createTime }}</a-descriptions-item>
        <a-descriptions-item label="更新时间">{{ resultDetail.updateTime }}</a-descriptions-item>
      </a-descriptions>
    </a-modal>

    <!-- 编辑评分结果弹窗 -->
    <a-modal
      v-model:visible="editVisible"
      @cancel="handleEditCancel"
      @ok="handleEditOk"
      :width="300"
      title="编辑评分结果">
      <a-form
        ref="editFormRef"
        :model="editForm"
        :rules="editFormRules"
        hide-asterisk
        @submit="handleEditOk">
        <a-form-item field="resultPicture" hide-label>
          <cover-uploader v-model="editForm.resultPicture" ref="editRefUploader"/>
        </a-form-item>
        <a-form-item field="resultName" hide-label validate-trigger="blur">
          <a-input v-model="editForm.resultName" placeholder="请输入结果名称"/>
        </a-form-item>
        <a-form-item field="resultDesc" hide-label validate-trigger="blur">
          <a-textarea
            v-model="editForm.resultDesc"
            placeholder="请输入结果描述"
            :max-length="100"
            show-word-limit
          />
        </a-form-item>
        <a-form-item field="resultProp" hide-label validate-trigger="blur">
          <a-input-tag v-model="editForm.resultProp" placeholder='请输入结果属性集合(Enter输入)' allow-clear @change="editFormTagsChange"/>
        </a-form-item>
        <a-form-item field="resultScoreRange" hide-label validate-trigger="blur">
          <a-input-number
            v-model="editForm.resultScoreRange"
            placeholder="请输入结果得分范围"
            :min="0"
            :step="1"
          />
        </a-form-item>
      </a-form>
    </a-modal>

    <a-modal
      v-model:visible="tipDialog"
      title="评分结果规则与提示"
      width="300"
    >
      <div>
        <p>1. 结果名称：必填项，不能超过50个字符。</p>
        <p>2. 结果描述：必填项，不能超过200个字符。</p>
        <p>3. 结果属性集合：必填项，请按照格式输入，如：[I,S,T,J]。</p>
        <p>4. 结果得分范围：必填项，必须为0 - 100之间的数字。</p>
      </div>
    </a-modal>
  </div>
</template>

<style scoped>
.card {
  margin: 20px 0;
}

.set-container {
  display: flex;
  justify-content: space-between;
  flex-wrap: wrap;
}

.select-container .btn, .button-container .btn {
  margin-right: 5px;
}

.detail-image {
  text-align: center;
  margin-bottom: 20px;
}
</style>
